package com.wan.data.mysql.util;

import com.wan.data.mysql.exception.DBInitializeException;

import java.util.Objects;

/**
 * 字段类型解析
 * 例如：int(11)
 * columnType=int
 * length=11
 * scale=0
 */
public class ColumnType {
    private final String sourceType;
    private final String columnType;
    private final long length;
    private final int scale;

    private ColumnType(String sourceType, String columnType, long length, int scale) {
        this.sourceType = sourceType;
        this.columnType = columnType;
        this.length = length;
        this.scale = scale;
    }

    public static ColumnType parse(String sourceType){
        sourceType = sourceType.toLowerCase();
        String[] split = sourceType.split("\\(");
        if(split.length != 1 && split.length != 2){
            throw new DBInitializeException("字段类型格式不正确:" + sourceType);
        }
        String columnType = split[0];
        long length = 0L;
        int scale = 0;
        if(split.length > 1){
            String prop = split[1];
            prop = prop.replace(")","");
            String[] propSplit = prop.split(",");
            length = Long.parseLong(propSplit[0]);
            if(propSplit.length > 1){
                scale = Integer.parseInt(propSplit[1]);
            }
        }
        return new ColumnType(sourceType,columnType,length,scale);
    }


    public String getSourceType() {
        return sourceType;
    }

    public String getColumnType() {
        return columnType;
    }

    public long getLength() {
        return length;
    }

    public int getScale() {
        return scale;
    }

    @Override
    public String toString() {
        return sourceType;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ColumnType that = (ColumnType) o;
        return Objects.equals(sourceType, that.sourceType);
    }

    @Override
    public int hashCode() {
        return Objects.hash(sourceType);
    }
}
